package com.cdd.oss.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.cdd.oss.service.OssService;
import com.cdd.oss.utils.ConstantPropertiesUtil;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {
    @Override
    public String uploadFileAvatar(MultipartFile file) {

        //工具类获取值
        String endpoint = ConstantPropertiesUtil.END_POINT;
        String accessKeyId = ConstantPropertiesUtil.KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;

        try {
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

            // 上传文件流。
            InputStream inputStream = file.getInputStream();
            //获取文件的名称
            String originalFilename = file.getOriginalFilename();
            //在文件名称里面添加随机唯一值 asd-5545-awd
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            String fileName = uuid + originalFilename;
            //文件按照日期分类 2021/01/31/.1.jpg
            //获取当前日期
            String datePath = new DateTime().toString("yyyy/MM/dd");
            fileName = datePath + "/" + fileName;
            //第一个参数表示bucketName,第二个表示上传到oss文件路径和文件名称 /a/bb/1.jpg,第三个是上传文件的输入流
            ossClient.putObject(bucketName, fileName, inputStream);
            // 关闭OSSClient。
            ossClient.shutdown();

            //路径返回，需要把上传到aliyunOSS路径手动拼接
            String url = "https://"+bucketName+"."+endpoint+"/"+fileName;

            return url;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }

    }
}
